<template>
  <div v-loading="loading" element-loading-text="加载中。。。">
    <el-card style="overflow:visible;">
      <el-form  :model="form" size="mini" :rules="rules" label-position="top" ref="form">
        <el-row :gutter="10">
          <el-col  :lg="4" :md="6">
            <el-form-item label='机构号' prop="branchId">
               <select-tree :is-strictly="false" v-model="form.branchId"  style="width:170px;" 
               :props='{id:"orgno",label: "cname",children: "children"}' :tree-data="brnoList"  
               placeholder="请选择机构"></select-tree>
            </el-form-item>
          </el-col>
          <el-col :lg="4" :md="6">
            <el-form-item label='一级业务类型' prop='AREFONE'>
              <el-select v-model="form.AREFONE" placeholder="请选择一级业务类型" @change="twoQuery">
                <el-option 
                key="index"
                label="全部"
                value="">
                </el-option>
                <el-option v-for="item in AREFONEList" 
                :key="item.FLOWID"
                :label="(item.FLOWID+'-'+item.FLOWNAME)"
                :value="item.FLOWID">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
           <el-col :md="6" :lg="4">
            <el-form-item label="二级业务类型" prop="AREFTWO">
              <el-select v-model="form.AREFTWO" filterable placeholder="请选择二级业务类型" @change="threeQuery">
                <el-option 
                key="index"
                label="全部"
                value="">
                </el-option>
                <el-option
                  v-for="item in AREFTWOList"
                  :key="item.FLOWID"
                  :label="(item.FLOWID+'-'+item.FLOWNAME)"
                  :value="item.FLOWID"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="6" :lg="4">
            <el-form-item label="三级业务类型" prop="ARETHREE">
              <el-select v-model="form.ARETHREE" filterable placeholder="请选择三级业务类型">
                <el-option
                  v-for="item in ARETHREEList"
                  :key="item.FLOWID"
                  :label="(item.FLOWID+'-'+item.FLOWNAME)"
                  :value="item.FLOWID"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="6" :lg="4">
              <el-form-item label='开始日期' class='typeInfo-el-form-item' prop='startdate'>
                <el-date-picker v-model="form.startdate" style="width:100%;" value-format="yyyyMMdd" @change="dateChange" type="date" placeholder="选择开始日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :md="6" :lg="4">
              <el-form-item label='结束日期' class='typeInfo-el-form-item' prop='enddate'>
                <el-date-picker v-model="form.enddate" style="width:100%;" value-format="yyyyMMdd" @change="dateChange" type="date" placeholder="选择结束日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
          <el-col :lg="2" :md="3"  class="searchBtnMarginTop">
            <el-button type="primary" icon="el-icon-search" :loading="loading" size="mini" @click="query(1)">查询</el-button>
          </el-col>
          <el-col :md="3" :lg="2" class="searchBtnMarginTop">
            <el-button type='warning' size='mini' icon='el-icon-refresh' @click="clearForm('form')">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card style="margin-top:10px;">
      <el-row :gutter="10">
        <el-col :lg="2" :md="3" v-if="btnPermission('Button_User_Download')">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-download"
            :load="this.download"
            :disabled="tableData.length==0"
            @click="getExcel"
          >导出</el-button>
        </el-col>
      </el-row>
      <el-table
        :data="tableData"
        ref="table"
        border
        class="tableMarginTop"
        header-row-class-name="tableHeaderClass"
        highlight-current-row
        @selection-change="rowDate">
        <el-table-column type="selection" width="40px"></el-table-column>
        <el-table-column prop="AREANOID" label="机构号"></el-table-column>
        <el-table-column prop="AREANONAME" label="机构名称"></el-table-column>
        <el-table-column prop="AREANOTYPE" label="机构类型"></el-table-column>
        <el-table-column prop="DEVICEID" label="终端编号"></el-table-column>
        <el-table-column prop="BUSINESSTYPE" label="业务类型"></el-table-column>
        <el-table-column prop="BUSINESSCOUNT" label="业务量"></el-table-column>
        <el-table-column prop="CALLDATE" label="日期"></el-table-column>
      </el-table>
      <div style="text-align:right;margin-top:20px;" v-show="this.tableData">
        <el-pagination
          @size-change="handleSizeChange"
          :page-sizes="[10,25,50,100]"
          :page-size="pageSize"
          @current-change="changePage"
          :current-page="currentPage"
          layout="total,sizes, prev, pager, next, jumper"
          background
          :total="totalRcrdNum"
        ></el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import toolBox from "@/common/utils/toolBox";
import query from "@/message/siteManagement/businesstype/query";
import request1 from "@/common/utils/request";
import request from "@/common/utils/requestYg";
import getGlobalParams from "@/common/utils/getGlobalParams";
import branchList from "@/message/shared/branch-list"; //机构号
import selectTree from "@/components/selectTree3/";
import typeQuery from "@/message/siteManagement/businesstype/typeQuery";
export default {
  name: "",
  components: { selectTree },
  data() {
    return {
      pageSize: undefined, //表格每页的条数
      brnoList: [],
      AREFONEList: [],
      AREFTWOList: [],
      ARETHREEList: [],
      isNull: false,
      form: {
        //表单数据
        branchId: [],
        AREFONE: "",
        AREFTWO: "",
        ARETHREE: "",
        startdate: "",
        enddate: ""
      },
      rules:{
        startdate: [{ 
          required: true, 
          message: "开始日期不能为空", 
          trigger: "blur" 
        }],
        enddate: [{
          required: true,
          message: "结束日期不能为空",
          trigger: "blur"
        }],
      },
      total: 0,
      download: false,
      agentList: [],
      teamList: [],
      companyList: [],
      currentRow: [], //表格当前选中行
      currentPage: 1, //表格当前页
      totalRcrdNum: 0,
      tableData: [], //表格 数据
      loading: false, //loading遮罩
      filename: "",
      fileUrl: getGlobalParams.get("agentDownloadAddress"),
    };
  },
  computed: {},
  created: function() {
    this.pageSize = getGlobalParams.get("PageSize");
    this.form.startdate = toolBox.getNowTime(0);
    this.form.enddate = toolBox.getNowTime(0);
    this.initList();
    this.oneQuery();
  },
   watch: {
  },
  methods: {
    oneQuery(){
      //模板配置查询
      let resBody = new typeQuery();
      resBody.data.SUPERID = "0";
      request(resBody)
        .then(response => {
          // console.log("response", response);
          if (response.SYS_HEAD.ReturnCode === "000000") {
            this.AREFONEList = response.RSP_BODY.struct || [];
            
          } else {
            this.$message({
              type: "error",
              message: response.SYS_HEAD.ReturnMessage
            });
            this.AREFONEList=[];
          }
          this.loading = false;
        })
        .catch(error => {
          this.loading = false;
        })
    
    },
    
    //数据模板ID初始化下拉框
     twoQuery(val){
       if(val === "") {
         this.AREFTWOList = [];
         this.ARETHREEList = [];
         this.form.AREFTWO = "";
         this.form.ARETHREE = "";
       } else {

         this.AREFTWOList = [];
         this.ARETHREEList = [];
         this.form.AREFTWO = "";
         this.form.ARETHREE = "";
         let resBody = new typeQuery();
         resBody.data.SUPERID = val;
         request(resBody)
           .then(response => {
             console.log("response", response);
             if (response.SYS_HEAD.ReturnCode === "000000") {
               this.AREFTWOList = response.RSP_BODY.struct || [];
             } else {
               this.$message({
                 type: "error",
                 message: response.SYS_HEAD.ReturnMessage
               });
               this.ARETHREEList=[];
             }
           })
           .catch(error => {
           })
       }
    },
    //查询坐席
    threeQuery(val){
      this.ARETHREEList = [];
      this.form.ARETHREE = "";
      let resBody = new typeQuery();
      resBody.data.SUPERID = val;
      request(resBody)
        .then(response => {
          if (response.SYS_HEAD.ReturnCode === "000000") {
            this.ARETHREEList = response.RSP_BODY.struct || [];
            // console.log("if is null", this.ARETHREEList.length === 0);
            if(this.ARETHREEList.length === 0) {
              this.isNull = true;
            } else {
              this.isNull = false;
            }
          } else {
            this.$message({
              type: "error",
              message: response.SYS_HEAD.ReturnMessage
            });
            this.AREFTWOList=[];
          }
          this.loading = false;
        })
        .catch(error => {
          this.loading = false;
        })
    
    },
    initList() {
      //机构下拉框初始化
      let resBody = new branchList();
      resBody.data.orgno = this.$store.getters.BranchNum;
      request1(resBody)
        .then(response => {
          this.brnoList = response.RspInfo.Result || [];
          this.brnoMap = response.RspInfo.orgMap || {};
          this.brnoList = toolBox.formatTreeData(
            this.brnoList,
            "orgno",
            "superno"
          );
        })
        .catch(error => {
          console.error("查询错误", error);
        });
    },
    query(num){
      this.$refs["form"].validate(valid => {
        if(valid) {
          this.loading = true;
          this.currentPage = num;
          let resBody = new query();
          let list = "";
          if(this.form.branchId != null) {
              for(let i = 0; i < this.form.branchId.length; i++) {
                if(i == 0) {
                  list ="'" + this.form.branchId[i] + "'";
                } else {
                  list = list+ "," + "'" + this.form.branchId[i] + "'";
                }
              }
              //console.log("=============" + this.form.BRNO.length);
            }
          resBody.data.AREANOID = list,
          resBody.data.AREFONE = this.form.AREFONE,
          resBody.data.AREFTWO = this.form.AREFTWO;
          resBody.data.STARTDATE = this.form.startdate;
          resBody.data.ENDDATE = this.form.enddate;
          if(this.isNull == true) {
            resBody.data.THRISNULL = "0";
          } else {
            resBody.data.THRISNULL = "1";
          }
          resBody.data.ARETHREE = this.form.ARETHREE;
          resBody.data.ISOUTPUT = "0";
          resBody.data.pageflag = 4;
          resBody.data.currpage = this.currentPage;
          resBody.data.pagerownum = this.pageSize;
          request(resBody)
            .then(response => {
            console.log("返回信息"+response)
              if (response.SYS_HEAD.ReturnCode === "000000") {
                this.tableData = response.RSP_BODY.struct || [];
                this.totalRcrdNum = response.RSP_BODY.TotalNum;
              } else {
                this.$message({
                  type: "error",
                  message: response.SYS_HEAD.ReturnMessage
                });
                this.tableData=[];
              }
              this.loading = false;
            })
            .catch(error => {
              this.loading = false;
            })
          } else {
          this.$message({
            type: "warning",
            message: "请输入合法的数据！"
          });
          return false;
        }
      });
    },
    downFile(){
      this.download = false;
      if(this.filename.length==0){
        this.$message({
            type: "error",
            message: `文件不存在，无法下载`
        });

      }else{
        window.location.href = this.fileUrl + this.filename;
      }
    },
    getExcel(){
      this.$refs["form"].validate(valid => {
        if(valid) {
          this.$message({
            type: "success",
            message: `正在下载。。。。。。`
          }); 
          this.download = true;
          let resBody = new query();
          let list = "";
          if(this.form.branchId != null) {
              for(let i = 0; i < this.form.branchId.length; i++) {
                if(i == 0) {
                  list ="'" + this.form.branchId[i] + "'";
                } else {
                  list = list+ "," + "'" + this.form.branchId[i] + "'";
                }
              }
              //console.log("=============" + this.form.BRNO.length);
            }
          resBody.data.AREANOID = list,
          resBody.data.AREFONE = this.form.AREFONE,
          resBody.data.AREFTWO = this.form.AREFTWO;
          if(this.isNull == true) {
            resBody.data.THRISNULL = "0";
          } else {
            resBody.data.THRISNULL = "1";
          }
          resBody.data.ARETHREE = this.form.ARETHREE;
          resBody.data.STARTDATE = this.form.startdate;
          resBody.data.ENDDATE = this.form.enddate;
          resBody.data.ISOUTPUT = "1";
          resBody.data.pageflag = 4;
          resBody.data.currpage = 1;
          resBody.data.pagerownum = this.totalRcrdNum;

          request(resBody)
          .then(response => {
            if(response.SYS_HEAD.ReturnCode === "000000"){
              this.filename = response.RSP_BODY.OUTURL;
              console.log("this.filename", this.filename);
              this.downFile();
            } else {
              this.$message({
                type: "error",
                message: response.SYS_HEAD.ReturnMessage
              });
            }
            this.loading = false;
          })
          .catch(error => {
            this.loading = false;
          })
        } else {
          this.$message({
            type: "warning",
            message: "请输入合法的数据！"
          });
          return false;
        }
      });
    },
     // 重置查询条件
    clearForm(item) {
      this.$refs["" + item].resetFields();
      this.form.startdate = toolBox.getNowTime(0);
      this.form.enddate = toolBox.getNowTime(0);
    },
    changePage(val) {
      // this.currentPage = val;
      this.query(val);
    },
    handleSizeChange(val){
      this.pageSize = val;
      this.query(1);
    },
    rowDate(val) {
      this.currentRow = val;
    },
    refreshTable() {
      //刷新数据并清除选中的数据
      this.query(1);
    },
    dateChange(){
      let date1 = new Date(toolBox.timeFormat2Date(this.form.startdate))/1000/3600/24;
      let date2 = new Date(toolBox.timeFormat2Date(this.form.enddate))/1000/3600/24;
      let sumDate = date2-date1;
      let currentdate = new Date(toolBox.timeFormat2Date(toolBox.getNowTime(0)))/1000/3600/24;
      let day1 = date2 - currentdate;
      
      if(sumDate < 0) {
          this.$message({
          type: "warning",
          message: "开始日期不能大于结束日期"
        })
        this.form.startdate = this.toolBox.getNowTime (-day1 + 30);
      }
      if(sumDate > 30) {
        this.$message({
          type: "warning",
          message: "开始日期和结束日期的跨度不能大于一个月"
        })
        this.form.startdate = this.toolBox.getNowTime (-day1 + 30);
      }
    }
  }
};
</script>


<style lang="scss" scoped>
.selectTree {
  min-width: 150px;
}
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}
.dialog-text {
  display: inline-block;
  width: 100%;
  text-align: center;
  color: red;
}       
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.el-card {
  width: 100%;
}
.el-form-item {
  margin-left: 30px;
}
.el-form-item1 {
  margin-left: 10px;
}
.box2-button {
  width: 80px;
}

.el-card {
  overflow: inherit;
}
</style>
